package com.xxg.fileshand.activity

import android.app.ProgressDialog
import android.os.Bundle
import android.os.Handler
import android.widget.CompoundButton
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.TimeUtils
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.OnSelectListener
import com.xxg.fileshand.app.App
import com.xxg.fileshand.app.SetInfo
import com.xxg.fileshand.base.BaseVMActivity
import com.xxg.fileshand.base.NoViewModel
import com.xxg.fileshand.base.ext.clickWithTrigger
import com.xxg.fileshand.base.ext.dataConvert
import com.xxg.fileshand.base.ext.getApiService
import com.xxg.fileshand.base.launch
import com.xxg.fileshand.bean.PDRequest
import com.xxg.fileshand.config.Config
import com.xxg.fileshand.constant.Constant
import com.xxg.fileshand.databinding.ActivitySettingBinding
import com.xxg.fileshand.ext.MapTypeAdapter
import com.xxg.fileshand.greendao.GreenDaoManager
import com.xxg.fileshand.net.RetrofitManager
import java.text.SimpleDateFormat
import java.util.UUID


//设置界面
class SettingActivity : BaseVMActivity<ActivitySettingBinding, NoViewModel>() {

    var userPage = 1
    var userRows = 0
    var readPage = 1
    var readRows = 0
    var caseNoPage = 1
    var caseNoRows = 0
    var wzInfoPage = 1
    var wzInfoRows = 0

    var progressDialog: ProgressDialog? = null
    var isUpdate = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        initViews()
        initUpdate()
    }

    override fun onLeftClick() {
        super.onLeftClick()
        onBackPressed()
    }

    override fun getMyTitle(): String {
        return "系统设置"
    }

    private fun initUpdate() {

        mBinding.rlUpdate.clickWithTrigger {
            if (isUpdate) {
                return@clickWithTrigger
            }

            XPopup.Builder(this)
                .asCenterList("同步数据", arrayOf("增量更新", "全量更新"), object : OnSelectListener{
                    override fun onSelect(position: Int, text: String?) {
                        if (position == 1) {
//                            GreenDaoManager.getDaoSession().caseNoDTODao?.deleteAll()
                            GreenDaoManager.getDaoSession().caseCodeDTODao?.deleteAll()
                            GreenDaoManager.getDaoSession().userDTODao?.deleteAll()
//                            GreenDaoManager.getDaoSession().wzInfoDTODao?.deleteAll()
                            GreenDaoManager.getDaoSession().filesInfoDTODao?.deleteAll()
                            GreenDaoManager.getDaoSession().inventoryTaskDTODao?.deleteAll()
                            GreenDaoManager.getDaoSession().readDTODao?.deleteAll()
                            SPUtils.getInstance().put(Constant.UPDATE_CASE_NO_TIME, "")
                            SPUtils.getInstance().put(Constant.UPDATE_USER_TIME, "")
                            SPUtils.getInstance().put(Constant.UPDATE_WZ_INFO_TIME, "")
                            SPUtils.getInstance().put(Constant.UPDATE_READ_TIME, "")
                            SPUtils.getInstance().put(Constant.CLICK_UPDATE_TIME, "")
                        }
                        isUpdate = true
                        userPage = 1
                        userRows = 0
                        readPage = 1
                        readRows = 0
                        caseNoPage = 1
                        caseNoRows = 0
                        wzInfoPage = 1
                        wzInfoRows = 0
                        postOfflineRequest()
                    }
                }).show()
        }
    }

    private fun postOfflineRequest() {
        launch({
            showDialog("离线数据上传中...")
            val gsonBuilder = GsonBuilder()
            gsonBuilder.registerTypeAdapter(
                object :
                    com.google.gson.reflect.TypeToken<Map<String, Any>>() {}.type,
                MapTypeAdapter()
            )
            val gson = gsonBuilder.create()
            GreenDaoManager.getOfflineRequestDTOList()?.forEach {
                try {
                    when (it.requestType) {
                        Constant.REQUEST_UP_WZ -> {
                            val map = gson.fromJson<Map<String, Any>>(
                                it.requestJson,
                                object :
                                    com.google.gson.reflect.TypeToken<Map<String, Any>>() {}.type
                            )
                            val rp = getApiService().onSaveInfo(map).dataConvert()
                            if (rp.result > 0) {
                                GreenDaoManager.deleteOfflineRequestDTO(it)
                            } else {
                                toast(rp.msg)
                            }
                        }

                        Constant.REQUEST_DOWN_WZ -> {
                            val map = gson.fromJson<Map<String, Any>>(
                                it.requestJson,
                                object :
                                    com.google.gson.reflect.TypeToken<Map<String, Any>>() {}.type,

                                )
                            val rp = getApiService().offSaveInfo(map).dataConvert()
                            if (rp.result > 0) {
                                GreenDaoManager.deleteOfflineRequestDTO(it)
                            } else {
                                toast(rp.msg)
                            }
                        }

                        //借阅 出库
                        Constant.REQUEST_BORROW_WZ -> {
                            val map = gson.fromJson<Map<String, Any>>(
                                it.requestJson,
                                object :
                                    com.google.gson.reflect.TypeToken<Map<String, Any>>() {}.type
                            )
                            val rp = getApiService().outboundSaveInfo(map).dataConvert()
                            if (rp.result > 0) {
                                GreenDaoManager.deleteOfflineRequestDTO(it)
                            } else {
                                toast(rp.msg)
                            }
                        }

                        //归还 入库
                        Constant.REQUEST_RETURN_WZ -> {
                            val map = gson.fromJson<Map<String, Any>>(
                                it.requestJson,
                                object :
                                    com.google.gson.reflect.TypeToken<Map<String, Any>>() {}.type
                            )
                            val rp = getApiService().inboundSaveInfo(map).dataConvert()
                            if (rp.result > 0) {
                                GreenDaoManager.deleteOfflineRequestDTO(it)
                            } else {
                                toast(rp.msg)
                            }
                        }

                        Constant.REQUEST_INVENTORY_WZ -> {
//                            val map = gson.fromJson<Map<String, Any>>(
//                                it.requestJson,
//                                object :
//                                    com.google.gson.reflect.TypeToken<Map<String, Any>>() {}.type
//                            ).toMutableMap()
                            val pdRequest =
                                Gson().fromJson<PDRequest>(it.requestJson, PDRequest::class.java)
                            val rp = getApiService().checkCheckSave(pdRequest).dataConvert()
                            if (rp.result > 0) {
                                GreenDaoManager.deleteOfflineRequestDTO(it)
                            } else {
                                toast(rp.msg)
                            }
                        }

                        Constant.REQUEST_REVERSE_WZ -> {
                            val map = gson.fromJson<Map<String, Any>>(
                                it.requestJson,
                                object :
                                    com.google.gson.reflect.TypeToken<Map<String, Any>>() {}.type
                            ).toMutableMap()
                            val rp = getApiService().moveSaveInfo(
                                map
                            ).dataConvert()
//                            toast(rp.remark)
                            if (rp.result > 0) {
                                GreenDaoManager.deleteOfflineRequestDTO(it)
                            } else {
                                toast(rp.msg)
                            }
//                            val map = Gson().fromJson<Map<String, Any>>(
//                                it.requestJson,
//                                object :
//                                    com.google.gson.reflect.TypeToken<Map<String, Any>>() {}.type
//                            ).toMutableMap()
//                            if (!map.containsKey("szWZCaseNoFrom")) {
//                                map["szWZCaseNoFrom"] = ""
//                            }
//                            if (!map.containsKey("szWZTMs")) {
//                                map["szWZTMs"] = ""
//                            }
//                            map["nStaffID"] = map["nStaffID"].toString().toDouble().toInt()
//                            val rp = getApiService().changeWZ(map)
//                            if (rp.result > 0) {
//                                GreenDaoManager.deleteOfflineRequestDTO(it)
//                            } else {
//                                toast(rp.msg)
//                            }
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    toast(e.message)
                }
            }
            canDialog()
            updateInventoryTask()
        }, {
            toast("离线数据上传未完全成功")
            canDialog()
            updateInventoryTask()
        })
    }

    private fun updateInventoryTask() {
//        launch({
//            showDialog("同步盘点任务中...")
//            val taskRp = getApiService().pdTask()
//            if (taskRp.result > 0 && taskRp.row > 0) {
//                val inventoryTaskDTO = InventoryTaskDTO()
//                inventoryTaskDTO.taskId = 1
//                inventoryTaskDTO.taskJson = Gson().toJson(taskRp.data)
//                GreenDaoManager.addInventoryTaskDTO(inventoryTaskDTO)
//            } else {
//                toast("同步盘点任务为空")
//            }
//            canDialog()
        showDialog("同步用户中...")
        updateUser()
//        }, {
//            toast("同步盘点任务失败")
//            canDialog()
//            showDialog("同步用户中...")
//            updateUser()
//        })
    }

    private fun updateUser() {

        launch({
            val userS = getApiService().syncUser(
                mapOf(
                    "reqId" to UUID.randomUUID().toString(),
                    "deviceId" to DeviceUtils.getUniqueDeviceId(),
                    "syncType" to "user",
                    "requestTime" to SPUtils.getInstance()
                        .getString(Constant.UPDATE_USER_TIME, "0001-1-1 0:00:00")
                )
            ).dataConvert()
//            userRows += userS.userInfo.size
            GreenDaoManager.addUserInfoDTOList(userS.userInfo)
            SPUtils.getInstance().put(
                Constant.UPDATE_USER_TIME,
                TimeUtils.getNowString(SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
            )
//            if (userS.total > userRows) {
//                userPage++
//                updateUser()
//            } else {
            canDialog()
            showDialog("同步人员数据中...")
            updateRead()
//            }
        }, {
//            SPUtils.getInstance().put(
//                Constant.UPDATE_USER_TIME,
//                TimeUtils.getNowString(SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
//            )
            canDialog()
            showDialog("同步人员数据中...")
            updateRead()
        })
    }

    //同步借阅人员信息
    private fun updateRead() {
        launch({
            val readS = getApiService().syncBorrow(
                mapOf(
                    "reqId" to UUID.randomUUID().toString(),
                    "deviceId" to DeviceUtils.getUniqueDeviceId(),
                    "syncType" to "borrower",
                    "requestTime" to SPUtils.getInstance()
                        .getString(Constant.UPDATE_READ_TIME, "0001-1-1 0:00:00")
                )
            ).dataConvert()
//            readRows += readS.data.size
            GreenDaoManager.addBorrowDTO(readS.userInfo)
            SPUtils.getInstance().put(
                Constant.UPDATE_READ_TIME,
                TimeUtils.getNowString(SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
            )
//            if (readS.row > readRows) {
//                readPage++
//                updateRead()
//            } else {
            canDialog()
            showDialog("同步层位数据中...")
            updateCaseNo()
//            }
        }, {
//            SPUtils.getInstance().put(
//                Constant.UPDATE_READ_TIME,
//                TimeUtils.getNowString(SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
//            )
            canDialog()
            showDialog("同步层位数据中...")
            updateCaseNo()
        })
    }

    //同步层位数据
    private fun updateCaseNo() {
        launch({
            val caseNos = getApiService().syncCase(
                mapOf(
                    "reqId" to UUID.randomUUID().toString(),
                    "deviceId" to DeviceUtils.getUniqueDeviceId(),
                    "syncType" to "case",
                    "pageIndex" to caseNoPage,
                    "pageTotalCount" to 1000,
                    "requestTime" to SPUtils.getInstance()
                        .getString(Constant.UPDATE_CASE_NO_TIME, "0001-1-1 0:00:00")
                )
            ).dataConvert()
            caseNoRows += caseNos.caseInfo.size
            GreenDaoManager.addCaseCodeDTOList(caseNos.caseInfo)
            if (caseNos.pageTotalCount == 1000) {
                caseNoPage++
                updateCaseNo()
            } else {
                SPUtils.getInstance().put(
                    Constant.UPDATE_CASE_NO_TIME,
                    TimeUtils.getNowString(SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                )
                canDialog()
                showDialog("同步档案数据中...")
                updateWzInfo()
            }
        }, {
//            SPUtils.getInstance().put(
//                Constant.UPDATE_CASE_NO_TIME,
//                TimeUtils.getNowString(SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
//            )
            canDialog()
            showDialog("同步档案数据中...")
            updateWzInfo()
        })

    }

    private fun updateWzInfo() {
        launch({
            val wzInfos = getApiService().syncFiles(
                mapOf(
                    "reqId" to UUID.randomUUID().toString(),
                    "deviceId" to DeviceUtils.getUniqueDeviceId(),
                    "syncType" to "archive",
                    "pageIndex" to wzInfoPage,
                    "pageTotalCount" to 1000,
                    "syncTime" to SPUtils.getInstance()
                        .getString(Constant.UPDATE_WZ_INFO_TIME, "0001-1-1 0:00:00")
                )
            ).dataConvert()
            wzInfoRows += wzInfos.archiveInfo.size
            GreenDaoManager.addFilesInfoDTOList(wzInfos.archiveInfo)
            if (wzInfos.pageTotalCount == 1000) {
                wzInfoPage++
                updateWzInfo()
            } else {

                canDialog()
                toast("数据同步完成")
                val time = TimeUtils.getNowString(SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                mBinding.tvUpdateTime.text = time
                SPUtils.getInstance().put(
                    Constant.UPDATE_WZ_INFO_TIME,
                    time
                )
                SPUtils.getInstance().put(Constant.CLICK_UPDATE_TIME, time)
                isUpdate = false
            }
        }, {
            val time = TimeUtils.getNowString(SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
//            SPUtils.getInstance().put(
//                Constant.UPDATE_WZ_INFO_TIME,
//                time
//            )
            SPUtils.getInstance().put(Constant.CLICK_UPDATE_TIME, time)
            canDialog()
            toast("档案数据同步失败，同步结束")
            isUpdate = false
        })

    }

    private fun initViews() {
        mBinding.tvUpdateTime.text =
            SPUtils.getInstance().getString(Constant.CLICK_UPDATE_TIME, "点击同步")
        mBinding.tvIpAddress.text = SPUtils.getInstance().getString(Constant.BASE_URL)
        val intA = arrayOfNulls<Int>(30)
        for (i in 1..30) {
            intA[i - 1] = i
        }
        mBinding.tvCaseScanPower.text = SetInfo.getScanCasePower().toString()
        mBinding.tvWzScanPower.text = SetInfo.getScanWzPower().toString()
        mBinding.tvCaseScanPower.clickWithTrigger {
            //生成一个1到30的array数组

            XPopup.Builder(this)
                .atView(it)
                .asAttachList(
                    intA.map { it.toString() }.toTypedArray(),
                    null
                ) { position, text ->
                    mBinding.tvCaseScanPower.text = text
                    SetInfo.setScanCasePower(text.toInt())
                }.show()
        }
        mBinding.tvWzScanPower.clickWithTrigger {
            XPopup.Builder(this).atView(it)
                .asAttachList(
                    intA.map { it.toString() }.toTypedArray(),
                    null
                ) { position, text ->
                    mBinding.tvWzScanPower.text = text
                    SetInfo.setScanWzPower(text.toInt())
                }.show()
        }

        mBinding.switchOfflineMode.isChecked = SetInfo.isOffline()
        mBinding.switchOfflineMode.setOnCheckedChangeListener(object :
            CompoundButton.OnCheckedChangeListener {
            override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
                SetInfo.setOffline(isChecked)
            }
        })

        mBinding.switchIgnoreWrongFrame.isChecked = SetInfo.isIgnoreWrongCase()
        mBinding.switchIgnoreWrongFrame.setOnCheckedChangeListener(object :
            CompoundButton.OnCheckedChangeListener {
            override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
                SetInfo.setIgnoreWrongCase(isChecked)
            }
        })

        mBinding.switchOpenJia.isChecked = SPUtils.getInstance().getBoolean(Constant.IS_OPEN_JIA)
        mBinding.switchOpenJia.setOnCheckedChangeListener(object :
            CompoundButton.OnCheckedChangeListener {
            override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
                SPUtils.getInstance().put(Constant.IS_OPEN_JIA, isChecked)
            }
        })

        mBinding.switchInOut.isChecked = SPUtils.getInstance().getBoolean(Constant.IS_IN_OUT)
        mBinding.switchInOut.setOnCheckedChangeListener(object :
            CompoundButton.OnCheckedChangeListener {
            override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
                if (buttonView != null && !buttonView!!.isPressed()) {
                    return;
                }
                XPopup.Builder(this@SettingActivity).asConfirm(
                    "确认切换出入库功能吗?", "切换成功将重启App", {
                        SPUtils.getInstance().put(Constant.IS_IN_OUT, isChecked)
                        Handler().postDelayed({
                            AppUtils.relaunchApp(true)
                        }, 1000)
                    }, {
                        mBinding.switchInOut.isChecked = !isChecked
                    }
                ).show()
            }
        })

        mBinding.switchGuide.isChecked = SPUtils.getInstance().getBoolean(Constant.IS_GUIDE)
        mBinding.switchGuide.setOnCheckedChangeListener(object :
            CompoundButton.OnCheckedChangeListener {
            override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
                if (buttonView != null && !buttonView!!.isPressed()) {
                    return;
                }
                XPopup.Builder(this@SettingActivity).asConfirm(
                    "确认切换上架指导功能吗?", "切换成功将重启App", {
                        SPUtils.getInstance().put(Constant.IS_GUIDE, isChecked)
                        Handler().postDelayed({
                            AppUtils.relaunchApp(true)
                        }, 1000)
                    }, {
                        mBinding.switchGuide.isChecked = !isChecked
                    }
                ).show()
            }
        })

        mBinding.switchFind.isChecked = SPUtils.getInstance().getBoolean(Constant.IS_FIND)
        mBinding.switchFind.setOnCheckedChangeListener(object :
            CompoundButton.OnCheckedChangeListener {
            override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
                if (buttonView != null && !buttonView!!.isPressed()) {
                    return;
                }
                XPopup.Builder(this@SettingActivity).asConfirm(
                    "确认切换档案查找功能吗?", "切换成功将重启App", {
                        SPUtils.getInstance().put(Constant.IS_FIND, isChecked)
                        Handler().postDelayed({
                            AppUtils.relaunchApp(true)
                        }, 1000)
                    }, {
                        mBinding.switchFind.isChecked = !isChecked
                    }
                ).show()
            }
        })

        mBinding.switchReverse.isChecked = SPUtils.getInstance().getBoolean(Constant.IS_REVERSE)
        mBinding.switchReverse.setOnCheckedChangeListener(object :
            CompoundButton.OnCheckedChangeListener {
            override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
                if (buttonView != null && !buttonView!!.isPressed()) {
                    return;
                }
                XPopup.Builder(this@SettingActivity).asConfirm(
                    "确认切换档案倒架功能吗?", "切换成功将重启App", {
                        SPUtils.getInstance().put(Constant.IS_REVERSE, isChecked)
                        Handler().postDelayed({
                            AppUtils.relaunchApp(true)
                        }, 1000)
                    }, {
                        mBinding.switchReverse.isChecked = !isChecked
                    }
                ).show()
            }
        })

        mBinding.tvIpAddress.clickWithTrigger {
            XPopup.Builder(this)
                .asInputConfirm(
                    "设置服务器IP地址",
                    null,
                    SPUtils.getInstance().getString(Constant.BASE_URL),
                    "x.x.x.x"
                ) {
                    if (it.isEmpty()) {
                        return@asInputConfirm
                    }
                    RetrofitManager.mRetrofitManager = null
                    SPUtils.getInstance().put(Constant.BASE_URL, it)
                    Config.baseUrl = it + "pda/commService/"
                }.show()
        }

        mBinding.rlClearDao.clickWithTrigger {
            GreenDaoManager.clearAll(false)
            toast("清除数据成功")
        }

        mBinding.rlClearData.clickWithTrigger {
            XPopup.Builder(this).asConfirm(
                "确认恢复出厂设置吗?", "恢复成功将重启App"
            ) {
                GreenDaoManager.clearAll(true)
                SPUtils.getInstance().clear()
                Handler().postDelayed({
                    AppUtils.relaunchApp(true)
                }, 1000)
            }.show()


        }
        mBinding.tvUnlogin.clickWithTrigger {
            App.nStaffID = 0
            AppUtils.relaunchApp(true)
        }
    }

    fun showDialog(title: String) {
        runOnUiThread {
            try {
                if (progressDialog == null) {
                    progressDialog = ProgressDialog(this);
                }
                if (progressDialog!!.isShowing()) {
                    return@runOnUiThread
                }
                progressDialog!!.setTitle(title)
                progressDialog!!.setMessage("Loading...")
                progressDialog!!.setCanceledOnTouchOutside(false)
                progressDialog!!.show();
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    //关闭进度圈圈
    fun canDialog() {
        if (progressDialog != null) {
            runOnUiThread {
                progressDialog?.cancel()
            }
        }
    }


}